package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private CategoryMapper categoryMapper;


    /**
     * 根据id删除分类，删除之前进行判断看是否关联其他表格
     * @param id
     * @return
     */
    @Override
    public R deleteById(Long id) {

        //select count(*) from dish where category_id = ? ;
        LambdaQueryWrapper<Dish> dishLqw = new LambdaQueryWrapper();
        dishLqw.eq(Dish::getCategoryId,id);
        int count = dishMapper.selectCount(dishLqw);

        //查询当前分类是否关联了dish，如果关联了，抛出一个业务异常
        if (count > 0){
            //抛出异常
            return R.error("当前分类下有菜品，不能删除！");
        }


        LambdaQueryWrapper<Setmeal> setmealLqw = new LambdaQueryWrapper<>();
        setmealLqw.eq(Setmeal::getCategoryId,id);
        int count1 = setmealMapper.selectCount(setmealLqw);
        //查询当前分类是否关联了Setmeal，如果关联了，抛出一个业务异常
        if (count1 > 0){
            //抛出异常
            return R.error("当前分类下有套餐，不能删除！");
        }


        //正常删除
        int i = categoryMapper.deleteById(id);

        return i > 0 ? R.success("分类删除成功") : R.error("分类删除失败");

    }
}
